<?php


namespace app\api\service;


use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\TokenException;
use think\Cache;
use think\Exception;
use think\Request;

class Token{

    public static function generateToken(){
        //32个字符组成随机字符串
        $randChars = random(32);
        //用三组字符串，进行md5加密
      //  $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        //salt 盐
        return md5($randChars);
    }

    //获取缓存中的具体数据uid，openid,session_key
    public static function getCurrentToken($key){
        $token = Request::instance()->header('token');
        $vars = Cache::get($token);
        if(!$vars){
            throw new TokenException();
        }

        if(!is_array($vars)){
            $vars = json_decode($vars,true);
        }

        if(!(array_key_exists($key,$vars))){
            throw new Exception('尝试获取的Token变量并不存在');
        }

        return $vars[$key];
    }

    //通过token获取用户uid
    public static function getCurrentUid(){
        $uid = self::getCurrentToken('uid');
        return $uid;
    }

    //获取token中的数据
    public function getToenValue($key){
        //接受到传入的token令牌
        //通过令牌到缓存中获取数据

        $token = Request::instance()->header('token');
        $tokenData = Cache::get($token);
        if(!$tokenData){
            die(json_encode(['msg'=>'对不起,获取数据失败']));
        }

        $tokenData = json_decode($tokenData,true);
        if(!(array_key_exists($key,$tokenData))){
            die(json_encode(['msg'=>'获取变量不存在']));
        }

        return $tokenData[$key];
    }

    //需要用户和CMS管理员 都可以访问接口的权限
    public static function needPrimaryScopr(){
        $scope = self::getCurrentToken('scope');

        if(!$scope){
            throw  new TokenException();
        }

        if($scope >= ScopeEnum::USER){
            return true;
        }else{
            throw new ForbiddenException();
        }
    }

    //只有用户才能访问的接口权限
    public static function needExclusiveScope(){
        //根据令牌获取缓存中的scope
        $scope = Token::getCurrentToken('scope');

        if(!$scope){
            throw  new TokenException();
        }

        if($scope == ScopeEnum::USER){
            return true;
        }else{
            throw new ForbiddenException();
        }

    }

    //验证当前使用的uid和缓存中的是否是同一个
    public static function isValidOperate($checkedUid){
        if(!$checkedUid){
            throw new Exception('用户id为空');
        }

        //获取缓存中的用户id
        $currentOperateUID = self::getCurrentUid();
        if($currentOperateUID == $checkedUid){
            return true;
        }
        return false;
    }



    //验证token的有效性
    public static function verifyToken($token){
        $exist = Cache::get($token);
        if($exist){
            return true;
        }else{
            return false;
        }
    }


}

















